#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008  Vladimir Lagunov

from config import *
import os
from time import localtime

class Logger:
    def __init__(self, logdir):
        self.logdir = logdir
        self.mdir = os.getcwd()
        self.ending = u'</body>\n</html>\n'
        self.logfile = None
        
    def openLogFile(self):
        if self.logfile:
            self.logfile.close()

        if not os.access(logdir, os.F_OK):
            os.mkdir(logdir)
        os.chdir(logdir)

        if not os.access(room, os.F_OK):
            os.mkdir(room)
        os.chdir(room)

        lt = localtime()
        if not os.access(unicode(lt[0]), os.F_OK):
            os.mkdir(unicode(lt[0]))
        os.chdir(unicode(lt[0]))

        if not os.access(unicode(lt[1]), os.F_OK):
            os.mkdir(unicode(lt[1]))
        os.chdir(unicode(lt[1]))

        if not os.access(unicode(lt[2])+'.html', os.F_OK):
            self.logfile = open(str(lt[2])+'.html', 'w')
            self.writeLogFileHead()
            self.logfile.close()
        self.logfile = open(str(lt[2])+'.html', 'r+')
        os.chdir(self.mdir)
        
    def writeLogFileHead(self):
        lt = list(localtime()[:3])
        lt.reverse()
        logfilehead = \
'''<html>
<head>
<META http-equiv="content-type" content="text/html; charset=utf-8">
<title>Журнал сообщений за %d/%d/%d</title>
</head>
<body>
<h2>Журнал сообщений за %d/%d/%d</h2>
''' % tuple(lt * 2)
        self.logfile.write(logfilehead)
        self.logfile.write(self.ending)
        self.logfile.seek(-len(self.ending), 2)

    def writeMessage(self, member, text):
        self.openLogFile()
        self.logfile.seek(-len(self.ending), 2)
        lt = localtime()[3:6]
        msg = u"<br>&#8237;<strong>[ %02d:%02d:%02d ] " % lt
        if member and member != room:
            msg += unicode(member.resource)
            if not text.startswith('/me'):
                msg += u':'
            msg += u'</strong> ' + unicode(text) + u'\n'
        else:
            msg += u'</strong><em> ' + unicode(text) + u'</em>\n'
        self.logfile.write(msg.encode('UTF-8'))
        self.logfile.write(self.ending)
        self.logfile.flush()
        os.chdir(self.mdir)
